package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.UserRegisterParam;
import com.example.lotterysystem.controller.result.UserRegisterResult;
import com.example.lotterysystem.service.UserService;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param param
     * @return
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param) {
        /**
         * 日志打印
         * 打印请求参数(param)相关的内容，有利于后续异常出现的排查
         * 这里打印一个 info 级别的日志，展示了哪个方法(userRegister)，哪个参数类型(UserRegisterParam)
         * 以及正文内容，使用 {} 占位符表示，希望 param 是以 json 字符串的方式打印，所以这里进行序列化
         */
        logger.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));

        // 调用 Service 层服务进行访问
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(converToUserRegisterResult(userRegisterDTO));
    }

    // 将 UserRegisterDTO 转换为 UserRegisterResult 类型返回
    private UserRegisterResult converToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        // 判断 userRegisterDTO 是否为空
        if (null == userRegisterDTO) {
            // 若为空，则抛出状态码为 100 的“注册失败”异常
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
